(function ($) {
    var me = {};
    var FormElement = function(element, options) {
		this.element = $(element);
		me = this;
		// 清空数据
		me.set('elementOption',[]);
		$.each(options,function(k,v){
			if( v == undefined && v == null ) return true;
			if( typeof v === 'object' ) {
				$.extend(me.get(k),v);
			} else {
				me.set(k,v);
			}
		});
		// 设置配置
		me.set('formId',this.element.attr('id'));
    };
    /**
     * 默认配置
     */
    FormElement.prototype = {
        constructor: FormElement,
		// 设置
		set: function(key,val){
			this[key] = val;
			return this;
		},
		// 获取
		get: function(key){
			return this[key];
		},
		// 是否自动加载
		autoLoad: true,
		// 表单ID
		formId: "",
		// 表单配置
		elementOption: [],
		// 表单元素模板
		elementTpl: '<div class="form-group">' +
				'<label class="col-sm-3 control-label no-padding-right" for="form-field-2">{2}{0}：</label>' +
				'<div class="col-sm-9">' +
					'{1}' +
				'</div>' +
			'</div>' +
			'<div class="space-4"></div>',
		// 标记模板
		markTpl: '<span class="red">*</span>',
		// 提示模板
		tipsTpl: ' data-rel="tooltip" data-placement="bottom" ',
		// input模板
		inputTpl: '<input type="{0}" id="{1}" name="{2}" class="{3}" value="{4}" placeholder="{5}" {6} {7} {10} {11} data-original-title="{12}" />',
		// input组装
		inputBuild: function(option){},
		// input渲染
		inputRender: function( option ){},
		// date模板
		datetimeTpl: '<div class="input-group">' +
					'<input type="text" id="{1}" name="{2}" class="{3}" value="{4}" data-placeholder="{5}" {6} {7} data-date-format="{8}" {10} {11} data-original-title="{12}" />' +
					//'<span class="input-group-addon">' +
					//	'<i class="fa fa-calendar bigger-110"></i>' +
					//'</span>' +
				'</div>',
		// datetime组装
		datetimeBuild: function(option){},
		// datetime渲染
		datetimeRender: function( option ){
			$('#' + option.id).datetimepicker({
				//format: 'YYYY/MM/DD HH:mm:ss',//use this option to display seconds
				icons: {
					time: 'fa fa-clock-o',
					date: 'fa fa-calendar',
					up: 'fa fa-chevron-up',
					down: 'fa fa-chevron-down',
					previous: 'fa fa-chevron-left',
					next: 'fa fa-chevron-right',
					today: 'fa fa-arrows ',
					clear: 'fa fa-trash',
					close: 'fa fa-times'
				}
			}).next().on(ace.click_event, function(){
				$(this).prev().focus();
			});
		},
		// select模板
		selectTpl: '<select id="{1}" name="{2}" class="{3}" data-placeholder="{5}" {9} >' +
					'{4}' +
				'</select>',
		// select组装
		selectBuild: function(option){
			var list = {}, html = option.multiple ? '' : '<option value="">' + ( option.placeholder != '' ? option.placeholder : "" ) + '</option>';
			if( typeof(option.data) == "object" ) {
				$.each(option.data,function(key,val){
					if( typeof(val) == "object" ) {
						list[val[option.fieldKey]] = val[option.fieldValue];
					} else if( typeof(val) == "string" ) {
						list[key] = val;
					}
				});
			} else if( typeof(option.data) == "string" ) {
				$.ajax({
					type: "get",
					dataType: "json",
					url: option.data,
					data: option.dataParam || {},
					async: false,
					success: function(data){
						var dataList = option.dataSrc != '' ? data.result : data ;
						$.each(dataList,function(key,val){
							if( typeof(val) == "object" ) {
								list[val[option.fieldKey]] = val[option.fieldValue];
							} else if( typeof(val) == "string" ) {
								list[key] = val;
							}
						});
					},
					error: function(data){}
				});
				
			}
			$.each(list,function(key,val){
				html += '<option ' + ( option.value == key ? "selected" : "" ) + ' value="' + key + '">' + val + '</option>';
			});
			return html;
		},
		// select渲染
		selectRender: function( option ){
			if( me.formId.indexOf("Search") != -1 ) return;
			if( ace.vars['touch']) return;
			$('#' + option.id).chosen({allow_single_deselect:true});
		},
		// text模板
		textareaTpl: '<textarea id="{1}" name="{2}" class="{3}" placeholder="{5}" {6} {7} {10} {11} data-original-title="{12}" >{4}</textarea>',
		// textarea组装
		textareaBuild: function(option){},
		// textarea渲染
		textareaRender: function( option ){},
		// file模板
		fileTpl: '<input type="file" id="{1}" name="{2}" class="{3}" value="{4}" placeholder="{5}" {6} {7} {9} {10} {11} data-original-title="{12} />',
		// file组装
		fileBuild: function(option){},
		// datetime渲染
		// file渲染
		fileRender: function( option ){
			var defaultOption = {
				style : 'well',
				no_file: '',
				btn_choose: '将文件拖放到此处或单击以选择',
				btn_change: null,
				no_icon: 'ace-icon fa fa-cloud-upload',
				icon_remove: null,
				roppable: false,
				droppable: true,
				thumbnail: 'small',//false | large | fit
				maxSize: 220000,//bytes
				allowExt: [],//["jpeg", "jpg", "png", "gif"],
				denyExt:[],
				allowMime: [],//["image/jpg", "image/jpeg", "image/png", "image/gif"],
				denyMime:[],
				onchange: null,
				before_change: null,
				before_remove: null,
			};
			$.extend(defaultOption,option.fileOption);
			$('#' + option.id).ace_file_input(defaultOption);
		},
		// 创建表单元素
		// {id:'id',title:'序号',type:"text"},
		// {id:'id',title:'序号',field:'id',type:"text",className:"input-small",value:'',placeholder:"序号",disabled:false,readonly:false},
		// {id:'datePicker',title:'时间',type:"date",format:"yyyy-mm-dd"},
		createElement: function(){
			$.each(me.elementOption,function(k,v){
				if( $.isEmptyObject(v) ) return true;
				var $form = me.element, inputType = '', html = '', render = function(){};
				var title = v.title || '', type = v.type || 'text', id = v.id || 'id', name = v.field || id, className = v.className || 'form-control', value = v.value || '', placeholder = v.placeholder || title, tooltip = v.tooltip || '';
				var disabled = v.disabled ? "disabled" : "", readonly = v.readonly ? "readonly" : "", format = v.format || '', multiple = v.multiple ? "multiple" : "", required = v.required ? "required" : "", requiredMark = v.required ? me.markTpl : "";
				// 时间类型
				if( v.type == 'datetime' ) {
					inputType = 'datetime';
					format = format || 'YYYY-MM-DD HH:mm:ss';
				} else if( v.type == 'select' ) {
					inputType = v.type;
					placeholder = v.placeholder = v.placeholder || "请选择...";
					value = me.selectBuild(v);
				} else if( v.type == 'textarea' ) {
					inputType = v.type;
					placeholder = v.placeholder = v.placeholder || "请输入...";
				} else if( v.type == 'file' ) {
					inputType = v.type;
					placeholder = v.placeholder = v.placeholder || "请选择...";
				} else {
					inputType = 'input';
				}
				html = me[inputType + 'Tpl'].format(type,id,name,className,value,placeholder,disabled,readonly,format,multiple,required,me.tipsTpl,tooltip);
				if( v.type != 'hidden' ) {
					html = me.elementTpl.format(title,html,requiredMark);
				}
				$form.append(html);
				// 渲染
				render = me[inputType + 'Render'] || render;
				render(v);
			});
		},
		// 创建Element
		load: function(){
			me.beforeLoad();
			me.createElement();
			me.afterLoad();
		},
		// 加载数据前操作
		beforeLoad: function(){},
		// 加载数据之后操作
		afterLoad: function(){
			$('[data-rel=tooltip]').tooltip({container:'body'});
			$('[data-rel=popover]').popover({container:'body'});
		},
    };
    /**
     * 扩展 Jquery 对象为 FormElement
     * @param option
     */
    $.fn.formElement = function(option){
        return this.each(function () {
            var $this = $(this),
                data = $this.data('formElement'),
                options = typeof option === 'object' && option;
            if (!data)  {
                $this.data('formElement', (data = new FormElement(this, $.extend({}, options))));
            }
            if (typeof option == 'string') {
                data[option]();
            }
            if(data.autoLoad){
                data.load();
            }
        });
    };
    /**
     * 属性返回对创建此对象的函数的引用
     */
    $.fn.formElement.Constructor = FormElement;

})(jQuery);


